package com.school.empsys.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.school.empsys.page.table.PageTableRequest;
import com.school.empsys.page.table.PageTableHandler;
import com.school.empsys.page.table.PageTableResponse;
import com.school.empsys.page.table.PageTableHandler.CountHandler;
import com.school.empsys.page.table.PageTableHandler.ListHandler;
import com.school.empsys.mapper.DictMapper;
import com.school.empsys.model.Dict;

@RestController
@RequestMapping("/dicts")
public class DictController {

	private static Logger logger = LoggerFactory.getLogger(DictController.class);

	@Autowired
	private DictMapper dictDao;

	/**
	 * 保存
	 * @param dict
	 * @return
	 */
	@RequiresPermissions("dict:add")
	@PostMapping
	public Dict save(@RequestBody Dict dict) {
		Dict d = dictDao.getByTypeAndK(dict.getType(), dict.getK());
		if (d != null) {
			throw new IllegalArgumentException("类型和key已存在");
		}
		dictDao.save(dict);

		return dict;
	}

	/**
	 * 根据id获取
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public Dict get(@PathVariable Long id) {
		return dictDao.getById(id);
	}

	/**
	 * 修改
	 * @param dict
	 * @return
	 */
	@RequiresPermissions("dict:add")
	@PutMapping
	public Dict update(@RequestBody Dict dict) {
		dictDao.update(dict);

		return dict;
	}

	/**
	 * 列表
	 * @param request
	 * @return
	 */
	@RequiresPermissions("dict:query")
	@GetMapping(params = { "start", "length" })
	public PageTableResponse list(PageTableRequest request) {
		return new PageTableHandler(new CountHandler() {

			@Override
			public int count(PageTableRequest request) {
				return dictDao.count(request.getParams());
			}
		}, new ListHandler() {

			@Override
			public List<Dict> list(PageTableRequest request) {
				return dictDao.list(request.getParams(), request.getOffset(), request.getLimit());
			}
		}).handle(request);
	}

	/**
	 * 删除
	 * @param id
	 */
	@RequiresPermissions("dict:del")
	@DeleteMapping("/{id}")
	public void delete(@PathVariable Long id) {
		dictDao.delete(id);
	}

	@GetMapping(params = "type")
	public List<Dict> listByType(@RequestParam(required = true) String type) {
		return dictDao.listByType(type);
	}
}
